#!/usr/bin/python
import os, xmpp, time, select
import readline
import sys
import imp

from jablit.commands import CommandAnalyzer
from jablit.listener import Listen
from jablit.client import Client

def main():
    jidparams = {}
    CONF_FILENAME = os.path.join(os.environ['HOME'], '.jablib_conf.py')
    try:
        conf = imp.load_source("conf", CONF_FILENAME)
    except IOError:
        open(CONF_FILENAME,'w').write("""jid = "romeo@montague.net/jablit"
password = "juliet"
server = "talk.google.com"
port = 5223
""")
        print 'Config file created: %s, edit it and run jablit' % CONF_FILENAME
        sys.exit(0)

    jid = xmpp.protocol.JID(conf.jid)
    cl = xmpp.Client(jid.getDomain(), debug=[])
    client = Client(cl, jid, conf.password, (conf.server, conf.port))

    online = 1
    listener = Listen(online, cl, client)

    readline.parse_and_bind("tab: complete")
    readline.parse_and_bind('"\C-r": reverse-search-history')

    cmd = CommandAnalyzer(cl, client)

    try:
        while online:
            instr = raw_input("> ")
            cmd.run_once(instr)
    finally:
        print "quitting..."
        online = 0
        cl.disconnect()
        sys.exit(0)

if __name__ == '__main__':
    main()
